package com.augmentum.oes.util;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.augmentum.oes.AppContext;

@Component
@Aspect
public class LogMethodAspect {

    private final static Logger logger = Logger.getLogger(LogMethodAspect.class);

    @Pointcut("execution(* com.augmentum.login.service..*(..))")
    private void logMethod() {
    };

    @Before("logMethod()")
    public void doBefore(JoinPoint jp) {
        logger.info("Begining method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());
    }

    @Around("logMethod()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Object returnValue = pjp.proceed();
        String methodName = pjp.getSignature().getName();
        StringBuilder sb = new StringBuilder();
        sb.append(AppContext.getContext().getUserName());
        sb.append(":");
        sb.append(pjp.getTarget().getClass().getSimpleName());
        sb.append(":");
        sb.append(methodName);
        logger.info(sb.toString());
        return returnValue;
    }

    @After("logMethod()")
    public void doAfter(JoinPoint jp) {
        logger.info("Ending method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());
    }

    @AfterThrowing(pointcut = "logMethod()", throwing = "ex")
    public void doAfterThrowing(JoinPoint jp, Throwable ex) {
        logger.error("method " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName()
                + " throw exception");
    }

}
